package yb.ecp.fast.infra.configs;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * springboot 在操作RedisTemplate时发现存储在redis中的key不是设置的string值，莫名的前缀乱码
 * 原因是spring-data-redis的RedisTemplate<K, V>模板类在操作redis时默认使用JdkSerializationRedisSerializer来进行序列化，
 * 导致默认加了乱码前缀，初始化时将key的序列化设置为StringRedisSerializer
 */
@Configuration
public class RedisTemplateConfig {

    @Primary
    @Bean("gwRedisTemplate")
    public RedisTemplate<Object, Object> getRedisTemplate(RedisTemplate<Object, Object> redisTemplate) {
        RedisSerializer<String> stringSerializer = new StringRedisSerializer();
        RedisSerializer<Object> JacksonSerializer = new GenericJackson2JsonRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(JacksonSerializer);
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setHashValueSerializer(JacksonSerializer);
        return redisTemplate;
    }
}
